<template>
  <div class="login-container">
    <div class="login-box">
      <h2>图书管理系统</h2>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item v-if="loginForm.username" prop="captchaCode">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captchaCode"
              placeholder="请输入验证码"
              style="width: 60%"
            />
            <img
              v-if="captchaImg"
              :src="captchaImg"
              alt="验证码"
              class="captcha-img"
              @click="getCaptcha"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            style="width: 100%"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        
        <div class="login-links">
          <el-link type="primary" @click="$router.push('/reset-password')">
            忘记密码？
          </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref()
const loading = ref(false)
const captchaImg = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captchaCode: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captchaCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 获取验证码
const getCaptcha = async () => {
  if (!loginForm.username) {
    captchaImg.value = ''
    return
  }
  
  try {
    const response = await request.get('/api/captcha', {
      params: { username: loginForm.username }
    })
    if (response.data && response.data.img) {
      captchaImg.value = response.data.img
      // 清空验证码输入框
      loginForm.captchaCode = ''
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败')
  }
}

// 监听用户名变化
watch(() => loginForm.username, (newVal) => {
  if (newVal) {
    getCaptcha()
  } else {
    captchaImg.value = ''
  }
})

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    console.log('登录请求数据:', loginForm)
    
    // 使用store的loginAction
    const result = await userStore.loginAction(loginForm)
    
    if (result.success) {
      console.log('用户状态更新成功')
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(result.message || '登录失败')
      // 登录失败时刷新验证码
      getCaptcha()
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败')
    // 登录失败时刷新验证码
    getCaptcha()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 页面加载时不自动获取验证码
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.login-form {
  width: 100%;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.login-links {
  text-align: center;
  margin-top: 20px;
}

/*
  测试用户信息：
  admin  13800138000
  test   15811238888
*/
</style> 